import { useState, useEffect, createRef } from "openinula";
import React from "react";
import { render, configure } from "../../rtl";

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error) {
        return { hasError: true };
    }

    componentDidCatch(error, info) {
        console.error("ErrorBoundary caught an error", error);
    }

    render() {
        if (this.state.hasError) {
            return <div>Error</div>;
        }
        return this.props.children;
    }
}

const Foo = () => {
    const [text, setText] = useState("text1");
    useEffect(() => {
        setTimeout(() => {
            setText("text2");
        }, 300);
    }, []);
    return <div>{text}</div>;
};

describe("render API", () => {
    let originalConfig
    beforeEach(() => {
        // Grab the existing configuration so we can restore
        // it at the end of the test
        configure(existingConfig => {
            originalConfig = existingConfig
            // Don't change the existing config
            return {}
        })
    })

    afterEach(() => {
        configure(originalConfig)
    })

    test("renders without crashing", () => {
        render(<Foo />);
    });

    test('renders div into document', () => {
        const ref = createRef()
        const { container } = render(<div ref={ref} />)
        expect(container.firstChild).toBe(ref.current)
    })
});